﻿using System;
using System.Threading;
using System.Threading.Tasks;
using K9Nano.Admin.Weixin.OAuth;
using K9Nano.Caching;
using K9Nano.Dependency;
using WeixinGateway.Remoting;

namespace K9Cloud.Admin.Weixin
{
    public class WeixinAppSettingManager : IWeixinAppSettingManager, ISingletonDependency
    {
        private readonly WeixinGateway.Remoting.WeixinService.WeixinServiceClient _client;
        private readonly ITypedCache<WeixinAppSettingInfo> _cache;

        public WeixinAppSettingManager(WeixinService.WeixinServiceClient client, ITypedCache<WeixinAppSettingInfo> cache)
        {
            _client = client;
            _cache = cache;
        }

        public ValueTask<WeixinAppSettingInfo> GetAsync(string clientId, CancellationToken cancellation)
        {
            throw new System.NotImplementedException();
        }

        public WeixinAppSettingInfo Get(string clientId)
        {
            var result = _cache.Get(clientId);

            if (result == null)
            {
                var reply = _client.GetAppSecret(new WeixinSettingRequest
                {
                    ClientId = clientId
                });

                if (reply != null)
                {
                    result = new WeixinAppSettingInfo
                    {
                        AppId = reply.AppId,
                        ClientId = clientId,
                        AppSecret = reply.AppSecret
                    };
                    _cache.Put(clientId, result, TimeSpan.FromMinutes(5));
                }
            }

            return result;
        }

        public ValueTask AddOrUpdateAsync(WeixinAppSettingInfo setting, CancellationToken cancellation)
        {
            throw new System.NotImplementedException();
        }

        public ValueTask DeleteAsync(string clientId, string appId, CancellationToken cancellation)
        {
            throw new System.NotImplementedException();
        }
    }
}